
cc.Class({
    extends: require('wy-Component'),

    properties: {
        scrollView :cc.ScrollView,
        editText :cc.EditBox,
        newMsgTag :cc.Node,
        chatItem : cc.Prefab,
        chatItemSelf : cc.Prefab
    },

    onLoad () {
        this.n_channel = null
        this.isLoop = false
        // this.n_channel = 'guild'+global.Data.id

    },
    start(){
        this.o_messages = [];
        this.n_firstTime = null;
        this.n_lastTime = null;
        this.newMsgTag.active = false
        this.scrollView.content.removeAllChildren();

        this.startLoop();
    },
    startLoop(){
        if(!this.isLoop && this.n_channel && this.n_channel != 'world'){
            this.httpGet('/game/gameUser/chat','list',{channel:this.n_channel},(err,res)=>{
                if(err){
                    return
                }
                if(this.n_firstTime==null && res.length){
                    this.n_firstTime = res[0].time
                }
                this.messages = res
                this.addMessageToBottom(res);
            })
    
            this.schedule(()=>{
                this.updateMessage();
            },2.0);
            this.isLoop = true;
        }
    },
    setChannel(c){
        this.n_channel = c
        this.startLoop();
    },

    onEnable(){
        this._super();
        this.scrollView.node.on("bounce-top", this.scorllToTop, this);
        this.scrollView.node.on("bounce-bottom", this.scrollToBottom, this);
    },
    onDisable(){
        this.scrollView.node.off("bounce-top",);
        this.scrollView.node.off("bounce-bottom");
    },
    scrollToBottom(){
        this.newMsgTag.active = false
        this.updateMessage();
    },

    scorllToTop(){
        this.httpGet('/game/gameUser/chat','list',{channel:this.n_channel,firstTime:this.n_firstTime},(err,res)=>{
            if(err){
                return
            }
            if(res.length >0){
                this.n_firstTime = res[0].time;
                this.messages = res.concat(this.messages)
                this.addMessageToTop();
            } else {
                this.scrollView.node.off("bounce-top", this.scorllToTop, this);
            }
        })
    },

    instantiateItem(msg,lasttime,idx){
        var node = msg._id==global.Data._id?cc.instantiate(this.chatItemSelf):cc.instantiate(this.chatItem);
        // cc.log('====',msg,global.Data)
        node.getComponent('UserInfo').setOptions(msg);

        node.isNew = !msg.isShow;
        if(node.isNew)
            node.opacity = 0;  //先隐藏一下，否则会闪一下
        
        if(msg.time-lasttime > 60*6000){
            var a = new Date(msg.time);
            var time = '';
            if(idx != 0){
                var b = new Date(lasttime);
                if(a.getFullYear() != b.getFullYear() || a.getMonth() != b.getMonth() || a.getDate() != b.getDate()){
                    time = a.getFullYear()+'-'+a.getMonth()+'-'+a.getDate()+' '
                }
            } else {
                time = a.getFullYear()+'-'+a.getMonth()+'-'+a.getDate()+' '
            }
            time += a.getHours()+':'+a.getMinutes()+':'+a.getSeconds();
            cc.find('panel/top/time',node).active = true;
            cc.find('panel/top/time',node).getComponent(cc.Label).string =  time
        }
        var lb_msg = cc.find('panel/msg/txt',node).getComponent(cc.Label);
        lb_msg.string = global.Common.subSectionString(msg.content,30);
        return node
    },    

    addMessageToTop(){ //从上向下拉，在顶部刷新历史消息
        this.scrollView.content.removeAllChildren();
        var lasttime = 0;
        for(var i=0; i<this.messages.length; i++){
            var msg = this.messages[i];
            var node = this.instantiateItem(msg,lasttime,i);
            this.scrollView.content.addChild(node);
            
            msg.isShow = true;
            lasttime = msg.time;
        }

        this.scheduleOnce(()=>{
            var height =0;
            var news = 0;
            var children = this.scrollView.content.children
            for(var i=0; i<children.length; i++){
                if(children[i].isNew){
                    children[i].runAction(cc.fadeIn(0.2)); //等调好位置先，再慢慢显示
                    height+=children[i].height
                    news++;
                }
                children[i].isNew = false;
            }
            cc.log('height:',news,height);
            this.scrollView.scrollToOffset(cc.v2(0,height),0.01);
        },0.01)
    }, 

    addMessageToBottom(){
        var offset = this.scrollView.getScrollOffset();
        var bl_autoScroll = false;
        var num_ch = this.scrollView.content.height
        var num_sh = this.scrollView.node.height
        if( num_ch < num_sh ||  (num_ch - num_sh - offset.y < 30)){
            bl_autoScroll = true;
        }
        var lasttime = 0;
        var bl_addNewMsg = false;

        for(var i=0; i<this.messages.length; i++){
            var msg = this.messages[i];
            if(!msg.isShow){
                var node = this.instantiateItem(msg,lasttime,i);
                this.scrollView.content.addChild(node);
                node.opacity = 255;
            }
            
            msg.isShow = true;
            lasttime = msg.time;
            bl_addNewMsg = true;
            this.n_lastTime = msg.time;
        }

        this.newMsgTag.active = false
        if(bl_autoScroll && bl_addNewMsg){
            var self = this;
            this.node.runAction(cc.sequence(cc.delayTime(0.1),cc.callFunc(function(no){
                self.scrollView.scrollToBottom(0.2)
            })));
        } else if(bl_addNewMsg && (num_ch - num_sh - offset.y > 30)){
            this.newMsgTag.active = true
        }
    },

    
    updateMessage(){
        var self = this
        this.httpGet('/game/gameUser/chat','newest',{channel:this.n_channel,lastTime:this.n_lastTime},(err,res)=>{
            if(err){
                return
            }
            if(res.length >0){
                self.n_lastTime = res[res.length-1].time
                self.messages = self.messages.concat(res)
                self.addMessageToBottom();
            } else {
                self.scrollView.node.off("bounce-top", self.scorllToTop, self);
            }
        })
    },

    sendObject(obj,cb){
        Object.assign(obj,{channel:this.n_channel})
        var msg = this.editText.string;
        // this.httpGet('/game/gameUser/chat','send',{channel:this.n_channel,type:0,context:msg},cb)
        this.httpGet('/game/gameUser/chat','send',obj,cb)
        
    },

    // onPageShow(){
    //     this.updateMessage()
    // }
});
